package com.jewaton.auth.security;

import com.jewaton.auth.dao.ResourcesDao;
import com.jewaton.auth.dao.UserDao;
import com.jewaton.auth.entity.Resources;
import com.jewaton.auth.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * 权限验证类
 *
 * 获得对象的方式：
 * WebUserDetails webUserDetails = (WebUserDetails)SecurityContextHolder.getContext().getAuthentication().getPrincipal();
 *
 * 或在JSP中：
 * <sec:authentication property="principal.username"/>
 *
 * 如果需要包括用户的其他属性，可以实现 UserDetails 接口中增加相应属性即可
 */
public class CustomUserDetailServiceImpl implements UserDetailsService {

    @Autowired
    private UserDao userDao;
    @Autowired
    private ResourcesDao resourcesDao ;
    // 登录验证
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //取得用户的权限,对象已实现UserDetails接口
        //在系统其它地方可以用
        //User user = (User) SecurityContextHolder.getContext().getAuthentication() .getPrincipal();
        //获得用户对象
        User users = userDao.querySingleUser(username);
        if  (users==null)
            throw new UsernameNotFoundException(username+" not exist!");
        Set<GrantedAuthority> grantedAuths = obtionGrantedAuthorities(users);
        //将权限插入用户对象
        users.setAuthorities(grantedAuths);

        // 封装成spring security的user
        /*User userdetail = new User(
                users.getUserName(),
                users.getUserPassword(),
                true,
                true,
                true,
                true,
                grantedAuths	//用户的权限
        );*/
        return users;
    }

    // 取得用户的权限
    private Set<GrantedAuthority> obtionGrantedAuthorities(com.jewaton.auth.entity.User user) {
        List<Resources> resources = resourcesDao.getUserResources(String.valueOf(user.getUserId()));
        Set<GrantedAuthority> authSet = new HashSet<GrantedAuthority>();
        for (Resources res : resources) {
            // 用户可以访问的资源名称（或者说用户所拥有的权限）
            // 以"ROLE_"开头
            authSet.add(new SimpleGrantedAuthority("ROLE_" + res.getResKey()));
        }
        return authSet;
    }

}
